#include "DMA2D.h"

static void configDMA2DParam(DMA2DParam &param);

void DMA2D_CopyYCbCrToRGB(DMA2DParam &param)
{
	configDMA2DParam(param);

	uint32_t destination = (uint32_t)param.pDst + ((param.y * param.xSize) + param.x) * 2; // 输出地址

	DMA2D->CR = 0x00010000UL | (1 << 9); // 存储器到存储器模式
	DMA2D->OOR = 0;

	/* 输出格式 */
	DMA2D->OPFCCR = param.outputPixelFormat | (DMA2D_REGULAR_ALPHA << 20) | (DMA2D_RB_REGULAR << 21);

	/* 前景层输入格式 */
	DMA2D->FGPFCCR = DMA2D_INPUT_YCBCR | (DMA2D_REPLACE_ALPHA << 16) | (DMA2D_REGULAR_ALPHA << 20) | 
		(DMA2D_RB_REGULAR << 21) | (0xFFU << 24) | (param.cssMode << 18);

	DMA2D->FGOR = param.inputLineOffset;
	DMA2D->NLR = (uint32_t)(param.xSize << 16) | (uint16_t)param.ySize;
	DMA2D->OMAR = (uint32_t)destination;
	DMA2D->FGMAR = (uint32_t)param.pSrc;

	DMA2D->CR |= DMA2D_CR_START; // 启动传输

	while (DMA2D->CR & DMA2D_CR_START); //	等待传输完成
}

static void configDMA2DParam(DMA2DParam &param)
{
	uint32_t cssMode = DMA2D_CSS_420;
	uint32_t inputLineOffset = 0;
	uint8_t bytePerPixel = 0;

	/* 处理输入行偏移 */
	switch (param.chromaSampling)
	{
	case JPEG_420_SUBSAMPLING:
		cssMode = DMA2D_CSS_420;
		inputLineOffset = param.xSize % 16;
		if (inputLineOffset != 0)
			inputLineOffset = 16 - inputLineOffset;
		break;
	case JPEG_444_SUBSAMPLING:
		cssMode = DMA2D_NO_CSS;
		inputLineOffset = param.xSize % 8;
		if (inputLineOffset != 0)
			inputLineOffset = 8 - inputLineOffset;
		break;
	case JPEG_422_SUBSAMPLING:
		cssMode = DMA2D_CSS_422;
		inputLineOffset = param.xSize % 16;
		if (inputLineOffset != 0)
			inputLineOffset = 16 - inputLineOffset;
		break;
	default:;
	}

	switch(param.outputPixelFormat)
	{
		case LTDC_PIXEL_FORMAT_RGB565:
			bytePerPixel = 2;
		break;
		case LTDC_PIXEL_FORMAT_ARGB8888:
			bytePerPixel = 4;
		break;
		default:;
	}

	param.cssMode = cssMode;
	param.inputLineOffset = inputLineOffset;
	param.bytePerPixel = bytePerPixel;
}